<template>
  <div style="width: 256px">
    <a-menu
      :default-selected-keys="['1']"
      :default-open-keys="['2']"
      mode="inline"
      :theme="theme"
      :inline-collapsed="collapsed"
    >
      <template v-for="item in menuData" :key="item.key">
        <template v-if="!item.children">
          <a-menu-item :key="item.path">
            <template #icon>
              <PieChartOutlined v-if="item.meta.icon" :type="item.meta.icon" />
            </template>
            {{ item.meta.title }}
          </a-menu-item>
        </template>
        <template v-else>
          <sub-menu :menu-info="item" :key="item.path" />
        </template>
      </template>
    </a-menu>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
import SubMenu from "./SubMenu";
import { PieChartOutlined } from "@ant-design/icons-vue";
// you can rewrite it to a single file component, if not, you should config vue alias to vue/dist/vue.esm-bundler.js
export default defineComponent({
  props: {
    theme: {
      type: String,
      default: "dark",
    },
  },
  data() {
    const menuData = this.getMenuData(this.$router.options.routes);
    return {
      menuData,
    };
  },
  methods: {
    getMenuData(routes) {
      const menuData = [];
      routes.array.forEach((item) => {
        if (item.name && !item.hideInMenu) {
          const newItem = { ...item };
          delete newItem.children;
          if (item.collapsed && item.hideChildrenInMenu) {
            newItem.children = this.getMenuData(item.children);
          }
          menuData.push(newItem);
        } else if (
          !item.hideInMenu &&
          !item.hideChildrenInMenu &&
          item.children
        ) {
          menuData.push(...this.getMenuData(item.children));
        }
      });
      return menuData;
    },
  },
  setup() {
    const collapsed = ref(false);

    const toggleCollapsed = () => {
      collapsed.value = !collapsed.value;
    };

    return {
      collapsed,
      toggleCollapsed,
    };
  },

  components: {
    "sub-menu": SubMenu,
    PieChartOutlined,
  },
});
</script>
